/* 
 * yulu-keji.com js base library 
 * copyright@ www.yulu-keji.com
 * 
 * events:
 * 		yulu.ui.rpeater.init
 * 		yulu.ui.repeater.creating [contents, list, $data]
 * 		yulu.ui.repeater.item.created [contents[i], list[i], $data]
 * 		yulu.ui.repeater.created [contents, list, $data]
 * 
 * 		yulu.ajax.success [data, textStatus, jqXHR]
 * 		yulu.ajax.error [jqXHR, ajaxSettings, thrownError]
 * 		yulu.ajax.complete [jqXHR, textStatus]
 * 		yulu.ajax.begin, [ajaxOptions]
 * 		yulu.ui.ajaxrpeater.init, ajaxRepeater
 * 
 * yulu.ui.plugins.selected  [$node, item]
 * yulu.ui.plugins.expand.expanded  [$node, item]
 * yulu.ui.plugins.expand.collapsed  [$node, item]
 * */

(function ($, yulu) {

    var ui = yulu("ui"),
        ajax = yulu("ajax"),
        core = yulu("core");

    var paginationConfig = yulu("ui.config.defaults.pagination"),
        plugins = yulu("ui.plugins");
    var Plugin = plugins.Plugins,
        registerPlugins = plugins.registerPlugins,
        AjaxTable = yulu("ui.components").AjaxTable,
        AjaxRepeater = yulu("ui.components").AjaxRepeater,
        Repeater = yulu("ui.components").Repeater;

    paginationConfig.first = "首页";
    paginationConfig.prev = "上一页";
    paginationConfig.next = "下一页";
    paginationConfig.last = "尾页";

    var AjaxSearchFormPlugins = plugins.AjaxSearchFormPlugins = function (selector) {
        Plugin.call(this, selector);
        this.ajaxRepeaterInit = function (ajaxRepeater) {
            var searchForm = $(selector).data("ajax-search-form");
            if (!searchForm) {
                return;
            }
            var formObject = $(searchForm).serializeObject();
            $(searchForm).on("submit", function () {
                formObject = $(searchForm).serializeObject();
                ajaxRepeater.reload();
                return false;
            });
            $(selector).on("yulu.ajax.begin", function (event, ajaxOptions) {
                ajaxOptions.data = $.extend(ajaxOptions.data, formObject);
            });
        }
    }

    var DataToggleInitPlugins = plugins.DataToggleInitPlugins = function (selector) {
        Plugin.call(this, selector);
        var self = this;
        this.ajaxRepeaterInit = function (ajaxRepeater) {
            var initLoad = $(selector).data("init-load");
            if (initLoad === true) {
                ajaxRepeater.reload();
            }
        }
    }

    var TwbsPaginationPlugins = plugins.TwbsPaginationPlugins = function (selector) {
        Plugin.call(this, selector);

        this.ajaxRepeaterInit = function (ajaxRepeater) {
            var pagination = $(selector).data("pagination");
            if (pagination === undefined && (ajaxRepeater instanceof AjaxTable)) {
                pagination = true;
            }
            if (!pagination) {
                return;
            }

            if (!$.fn.twbsPagination) {
                if (console && console.warn) { console.warn("!!!TwbsPaginationPlugins required twbsPagination library!!!") };
                return;
            }

            var options = core.getDataOptions(selector, "pagination");
            var $pagination = null;
            if (!options.target) {
                $pagination = $("<div>").insertAfter(selector);
            } else {
                $pagination = $(options.target);
            }
            options = $.extend({}, paginationConfig, options, core.getDataOptions($pagination, "pagination"));

            var pageIndex = 1;
            $(selector).on("yulu.ajax.begin", function (event, ajaxOptions) {
                ajaxOptions.data = $.extend(ajaxOptions.data, {pageIndex: pageIndex});
            });

            $(selector).on("yulu.ajax.success", function (event, data) {
                pageIndex = data.pageIndex || pageIndex;
                var totalPages = data.pageCount || 1;
                $pagination.twbsPagination('destroy');
                var init = false;
                $pagination.twbsPagination($.extend({}, options, {
                    startPage: pageIndex,
                    totalPages: totalPages,
                    onPageClick: function (event, page) {
                        if (page != pageIndex) {
                            pageIndex = page;
                            ajaxRepeater.reload();
                        }
                    }
                }));
            });
        }
    }

    var SelectedPlugins = plugins.SelectedPlugins = function (selector) {
        Plugin.call(this, selector);
        this.repeaterInit = function (repeater) {
            $(selector).on("yulu.ui.repeater.item.created", function (event, $node, item, source) {
                $node.find("[data-toggle=yulu-select]").unbind("click").on("click", function () {
                    $(selector).trigger({type: "yulu.ui.plugins.selected", source: this }, [$node, item]);
                    return false;
                });
            });
        }
    }

    var ExpandPlugins = plugins.ExpandPlugins = function (selector) {
        Plugin.call(this, selector);
        this.repeaterInit = function (repeater) {
            $(selector).on("yulu.ui.repeater.item.created", function (event, $node, item, source) {
                var $expands = $node.find("[data-toggle=yulu-expand]");
                if (!$expands.length) {
                    return;
                }
                var $target = $node.find("[data-toggle=yulu-expand-target]");
                var ajaxOptions = $.extend(ajax.getOptions(selector), ajax.getOptions($expands), ajax.getOptions($target));
                core.setDataOptions($target, ajaxOptions, "ajax");
                $expands.data("yulu-expand-target", $target);

                function toggleExpand($target, $expandElement) {
                    if ($target) {
                        var $expanded = $target.data("yulu-expand-state") || false;
                        $target.data("yulu-expand-state", $expanded = !$expanded);
                        var toggleClass = $expandElement.data("expand-toggle-class");
                        if (toggleClass) {
                            $expandElement.toggleClass(toggleClass)
                        }

                        var ajaxRepeater = $target.data("yulu-expand-repeater") || new AjaxRepeater($target, new Repeater($target, repeater.getTemplate(), true, true));
                        $target.data("yulu-expand-repeater", ajaxRepeater)
                        if ($expanded === true) {
                            // 判断是否有缓存
                            if (ajaxRepeater.getRepeater().fnHasCache()) {
                                ajaxRepeater.getRepeater().fnRenderCahce();
                            } else {
                                ajaxRepeater.reload();
                            }
                            $(selector).trigger({type: "yulu.ui.plugins.expand.expanded", source: this}, [$node, item]);
                        } else {
                            ajaxRepeater.getRepeater().fnRemoveItems();
                            $(selector).trigger({type: "yulu.ui.plugins.expand.collapsed", source: this}, [$node, item]);
                        }
                    }
                }

                $node.unbind("dblclick").on("dblclick", function () {
                    var $target = $node.find("[data-toggle=yulu-expand]").data("yulu-expand-target");
                    var $self = $node.find("[data-toggle=yulu-expand]");
                    toggleExpand($target, $self);
                    return false;
                });

                $(selector).find("[data-toggle=yulu-expand]").unbind("click").on("click", function () {
                    var $target = $(this).data("yulu-expand-target");
                    var $self = $(this);
                    toggleExpand($target, $self);
                    return false;
                });
            });
        }
    }

    var MuiltipleContainerPlugins = plugins.MuiltipleContainerPlugins = function (selector) {
        Plugin.call(this, selector);
        this.repeaterInit = function (repeater) {
            var targets = $(selector).data("container-target");
            if (!targets) {
                return;
            }
            $(selector).on("yulu.ui.repeater.rendered", function (event, contents, list, $data) {
                $(targets).each(function () {
                    var type = $(this).data("container-target-type") || "table";
                    if (type == "table") {
                        ui.table($(this), list, $data);
                    } else if (type == "list") {
                        ui.list($(this), list, $data);
                    } else if (type == "tree") {
                        ui.tree($(this), list, $data);
                    }
                });
            });
        }
    }

    var UserSelectedEventPlugins = plugins.UserSelectedEventPlugins = function (selector) {
        Plugin.call(this, selector);
        this.repeaterInit = function (repeater) {
            $(selector).on("yulu.ui.plugins.selected", function (event, $node, item) {
                var $source = $(event.source);
                if ($source.data("yulu-select-event")) {
                    var eventSrc = {type: $source.data("yulu-select-event"), source: event.source};
                    var params = core.getDataOptions($source, "yuluSelectEvent");
                    eventSrc = $.extend({}, params, eventSrc);
                    $(selector).trigger(eventSrc, [$node, item]);
                }
            });
        }
    }

    registerPlugins(AjaxSearchFormPlugins);
    registerPlugins(TwbsPaginationPlugins);
    registerPlugins(DataToggleInitPlugins);
    registerPlugins(ExpandPlugins);
    registerPlugins(SelectedPlugins);
    registerPlugins(MuiltipleContainerPlugins);
    registerPlugins(UserSelectedEventPlugins);

})(window.jQuery, window.yulu);

